<template>
  <div class="keynotes">
    <!-- <a v-for="item of list" :key="item.index" :href="'#d'+item.id" :title="item.name">{{item.id}}{{' . '+item.name}}</a> -->
    <p
      v-for="(item,index) of list"
      :key="index"
      :class="{active:cindex==index}"
      @click="jump(index)"
      :title="item.name"
    >{{item.id}}{{' . '+item.name}}</p>
  </div>
</template>
<script>
export default {
  name: "keynote",
  props: ["list"],
  data() {
    return {
      allHe: [],
      cindex: 0,
      timer: null
    };
  },
  watch:{
      list(v){
          if(v){
            this.init(v)
          }
      }
  },    
  mounted: function() {
      this.allHe=[];
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScroll);
  },
  methods: {
      init(v){
        document.querySelector(".container").scrollTop=0;
      this.cindex=0;
       this.allHe=[];
        setTimeout(()=>{
            let jump = document.querySelectorAll(".textcont .c_cox");
            for (let i of jump) {
                this.allHe.push(i.offsetTop);
            }
            window.addEventListener("scroll", this.onScroll, true); // 监听（绑定）滚轮滚动事件
        },10)
    },
    onScroll() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        let mt = document.querySelector(".container").scrollTop;
        this.allHe.forEach((item, i) => {
          if (mt >= item-10) {
            this.cindex = i;
          }
        });
      }, 100);
    },
    jump(num) {
      this.cindex = num;

      let total = this.allHe[num];
      let mt = document.querySelector(".container").scrollTop;
      let distance = Math.abs(parseInt(mt == "" ? 0 : mt));
      //  let distance =  document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
      // Chrome  Firefox Safari
      // 平滑滚动，时长500ms，每10ms一跳，共50跳
      let step = (total - distance) / 50;
      if (total > distance) {
        smoothDown();
      } else {
        step = (distance - total) / 50;
        smoothUp();
      }
      function smoothDown() {
        if (distance < total) {
          distance += step;
          document.querySelector(".container").scrollTop = distance;
          setTimeout(smoothDown, 10);
        } else {
          document.querySelector(".container").scrollTop = total;
        }
      }
      function smoothUp() {
        if (distance > total) {
          distance -= step;
          document.querySelector(".container").scrollTop = distance;
          setTimeout(smoothUp, 10);
        } else {
          document.querySelector(".container").scrollTop = total;
        }
      }
    }
  }
};
</script>
<style scoped>
a {
  display: block;
  line-height: 2;
}
p {
  cursor: pointer;
}
.active {
  color: red;
  font-weight: bold;
}
</style>